package com.hbsc.interceptor;

import com.hbsc.config.Constants;
import com.hbsc.service.UserService;
import com.hbsc.utils.WechartUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.util.Map;

/**
 * Created by xvdong on 2017-10-16.
 */
public class WiXinHandlerInterceptor implements HandlerInterceptor {
    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(WiXinHandlerInterceptor.class);
    @Autowired
    private UserService service;
    @Autowired
    private WechartUtil util;
    @Override
    public boolean preHandle(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse repoonse, Object o) throws Exception {
        Map user_info=(Map)request.getSession().getAttribute(Constants.USER_INFO);
        String code=request.getParameter("code");
        logger.info("code:"+code);
        String accessToken="";
        if(StringUtils.isEmpty(code)){
            String url = "http://" + request.getServerName() + request.getContextPath() + request.getServletPath();
            accessToken = util.codeLink(url);
            logger.info("sendRedirect: " + accessToken);
            repoonse.sendRedirect(accessToken);
            return false;
        }else {
            if(null==user_info&& !StringUtils.isEmpty(code)){
                Map accessMap=util.getAccessToken(code);
                accessToken=String.valueOf(accessMap.get("access_token"));
                String refreshToken=String.valueOf(accessMap.get("refresh_token"));
                String openId=String.valueOf(accessMap.get("openid"));
                Map userInfo=service.queryByOpenId(openId);
                Map wiXinUserInfo=null;
                if(null==userInfo){
                    wiXinUserInfo=util.getUserInfo(accessToken,openId);
                    String errorCode=String.valueOf(wiXinUserInfo.get("errcode"));
                    if(errorCode.length()>1){
                        Map refreshTokenMap=util.getRefreshToken(refreshToken);
                        accessToken=String.valueOf(refreshTokenMap.get("access_token"));
                        wiXinUserInfo=util.getUserInfo(accessToken,openId);
                    }
                    wiXinUserInfo.putAll(accessMap);
                    String headimgurl=String.valueOf(wiXinUserInfo.get("headimgurl"));
                    if(!StringUtils.isEmpty(headimgurl)) {
                        service.insert(wiXinUserInfo);
                        userInfo = wiXinUserInfo;

                    }
                }
                request.getSession().setAttribute(Constants.USER_INFO, userInfo);
            }else if(null==user_info){
                return false;
            }
        }
        return true;
    }

    @Override
    public void postHandle(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
